using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;

namespace LogAnalyzerIIS.Objects
{
	/// <summary>
	///  Encapsulates server properties
	/// </summary>
	public class ServerRecord
	{
		/// <summary>
		/// server name
		/// </summary>
		public string Name = "[New Server]";

		/// <summary>
		/// path to the server logs 
		/// </summary>
		public string Path = "";

		/// <summary>
		/// server alias (currently equal to the Name) 
		/// </summary>
		public string Alias = "";

		/// <summary>
		/// server user name 
		/// </summary>
		public string Username = "";

		/// <summary>
		/// server user password 
		/// </summary>
		public string Password = "";

		/// <summary>
		/// indicates whether server needs to be processed 
		/// </summary>
		public bool Enabled;

		/// <summary>
		/// list of the server applications 
		/// </summary>
		public List<WebApplication> WebApplications = new List<WebApplication>();

		/// <summary>
		///  Loads the server applications using Actives Directory
		/// </summary>
		public void LoadWebApplicationsFromActiveDirectory()
		{
			// clear the previous applications
			WebApplications.Clear();

			try
			{
				DirectoryEntry w3SVCEntry = new DirectoryEntry("IIS://" + this.Name + "/w3svc", this.Username, this.Password);

				foreach (DirectoryEntry Site in w3SVCEntry.Children)
				{
					if (Site.SchemaClassName == "IIsWebServer")
					{
						int webApplicationIndex = -1;
						for (int webApplicationsCounter = 0; webApplicationsCounter < WebApplications.Count; webApplicationsCounter++)
						{
							if (WebApplications[webApplicationsCounter].LogPath == "W3SVC" + Site.Name)
							{
								webApplicationIndex = webApplicationsCounter;
								break;
							}
						}

						if (webApplicationIndex == -1)
						{
							WebApplications.Add(new WebApplication());
							webApplicationIndex = WebApplications.Count - 1;
						}

						WebApplications[webApplicationIndex].Name = Site.Properties["ServerComment"].Value.ToString();
						WebApplications[webApplicationIndex].LogPath = "W3SVC" + Site.Name;
					}
				}
			}
			catch { }
		}

		public override string ToString()
		{
			return Name;
		}
	}
}
